package net.tmaize.service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import net.tmaize.dao.impl.BeforeDaoImpl;
import net.tmaize.entity.News_before;

public class ShowBefore extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		// 不缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", -1);
		try {
			String datepicker = request.getParameter("datepicker");
			SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy年M月d日");
			SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");

			String date = dateFormat2.format(dateFormat1.parse(datepicker));
			// 日期下限
			if (Integer.parseInt(date) < 20130520) {
				response.sendRedirect(request.getContextPath() + "/error.html");
				return;
			}
			// 日期上限
			else if (Integer.parseInt(dateFormat2.format(new Date())) < Integer.parseInt(date)) {
				response.sendRedirect(request.getContextPath() + "/error.html");
				return;
			}
			BeforeDaoImpl beforeDaoImpl = new BeforeDaoImpl();
			News_before before = beforeDaoImpl.getBefore(date);
			request.setAttribute("before", before);
			RequestDispatcher requestDispatcher = this.getServletContext()
					.getRequestDispatcher("/WEB-INF/jsp/before.jsp");
			requestDispatcher.forward(request, response);
		} catch (ParseException | JSONException e) {
			response.sendRedirect(request.getContextPath() + "/error.html");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
